package cn.pugle.common.compress;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 使用jdk包压缩zip格式多个文件
 * @author tzp
 * @since 2018/2/1
 */
public class JDKZip {
    private static void zipFiles() {
        try {
            String zipFileName = "/Users/tzp/Documents/private/cnm/CodeAccumulate/target/test.zip";

            FileOutputStream fos = new FileOutputStream(zipFileName);
            ZipOutputStream zos = new ZipOutputStream(fos);

            String dir = "/Users/tzp/Documents/private/cnm/CodeAccumulate/src/main/java/cn/pugle/httpcomponent/";
            File dir_ = new File(dir);

            for (String aFile : dir_.list()) {
                zos.putNextEntry(new ZipEntry(new File(aFile).getName()));

                byte[] bytes = Files.readAllBytes(Paths.get(dir + aFile));
                zos.write(bytes, 0, bytes.length);
                zos.closeEntry();
            }
            zos.close();
        } catch (FileNotFoundException ex) {
            System.err.println("A file does not exist: " + ex);
        } catch (IOException ex) {
            System.err.println("I/O error: " + ex);
        }
    }

    public static void main(String[] args) {
        zipFiles();
    }
}
